peripolos = {};

peripolos.isActive = function() {
	return peripolos.hasOwnProperty('active');
}

peripolos.oxiActive = function() {
	return !peripolos.isActive();
}

peripolos.ergasia = {
	feredata: { period: 10000, action: Service.feredata.check },
	sinedria: { period: 21000, action: Service.sinedria.check },
	dbconn: { period: 12000, action: DB.check },
};

;(function() {
	Log.print('Calculating session timeouts');
	Log.level.push();

	Service.feredata.timeout = 2 * Math.floor(peripolos.ergasia.feredata.period / 1000) - 1;
	Log.print('timeout for "feredata" set to ' + Service.feredata.timeout + ' seconds');

	Service.sinedria.timeout = Service.feredata.timeout + Math.floor(peripolos.ergasia.feredata.period / 1000) - 1;
	Log.print('timeout for "sinedria" set to ' + Service.sinedria.timeout + ' seconds');

	Log.level.pop();
})();

peripolos.startup = function(skiniko) {
	var i;

	if (peripolos.isActive()) globals.fatal('patrol jobs reactivated');
	peripolos.active = true;

	Log.print('initializing patrol jobs');
	Log.level.push();
	for (i in peripolos.ergasia) {
		Log.print('initializing "' + i + '" check (every ' + peripolos.ergasia[i].period + ' ms)');
		eval('peripolos.ergasia["' + i + '"].timer = setInterval(function() {' +
			'peripolos.ergasia["' + i + '"].action(skiniko);' +
		'}, peripolos.ergasia["' + i + '"].period);');
	}
	Log.level.pop();
}

peripolos.suspend = function() {
	var i;

	if (peripolos.oxiActive()) return;
	delete peripolos.active;

	Log.print('suspending patrol jobs');
	Log.level.push();
	for (i in peripolos.ergasia) {
		if (!peripolos.ergasia[i].hasOwnProperty('timer')) continue;
		Log.print('suspenidng "' + i + '" check');
		clearInterval(peripolos.ergasia[i].timer);
	}
	Log.level.pop();
}
